package dq.study.minimvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class HandlerExecutionChain<T> {
    private T handler;
    private List<HandlerInterceptor> interceptors;

    public T getHandler() {
        return handler;
    }

    public HandlerExecutionChain(T handler) {
        this(handler,new ArrayList<>());
    }

    public HandlerExecutionChain(T handler, List<HandlerInterceptor> interceptors) {
        this.handler = handler;
        this.interceptors = interceptors;
    }

    public void addInterceptor(HandlerInterceptor interceptor) {
        this.interceptors.add(interceptor);
    }


    public void addInterceptors(List<HandlerInterceptor> interceptors) {
        this.interceptors.addAll(interceptors);
    }


    void applyPostHandle(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        for (HandlerInterceptor handlerInterceptor: interceptors) {
            handlerInterceptor.postHandle(request,response,handler);
        }
    }

    boolean applyPreHandle(HttpServletRequest processedRequest, HttpServletResponse response) throws Exception {
        for (HandlerInterceptor handlerInterceptor: interceptors) {
            if (!handlerInterceptor.preHandle(processedRequest,response,handler)){
                triggerAfterCompletion(processedRequest,response,null);
                return false;
            }
        }
        return true;
    }

    private void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
        for (HandlerInterceptor handlerInterceptor: interceptors) {
            handlerInterceptor.afterCompletion(request,response,handler,ex);
        }
    }
}
